package com.tedu.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.tedu.admin.mapper.AdminMapper;
import com.tedu.admin.pojo.entity.Admin;
import com.tedu.admin.service.AdminService;
import com.tedu.common.exception.ServiceException;
import com.tedu.common.jwt.JwtUtil;
import com.tedu.common.jwt.Payload;
import com.tedu.common.response.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Override
    public Map accountLogin(Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");

        if(StrUtil.isBlank(username) || StrUtil.isBlank(password)){
            throw new ServiceException(StatusCode.PARAM_VERIFICATION_FAILED);
        }

        Admin admin = adminMapper.findByUsername(username);
        if(admin==null){
            throw new ServiceException(StatusCode.USERNAME_ERROR);
        }

        if(!admin.getPassword().equals(password)){
            throw new ServiceException(StatusCode.PASSWORD_ERROR);
        }

        Payload payload = new Payload();
        payload.setAdmin(admin);
        String token = JwtUtil.generateToken(payload);

        Map<Object, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("admin", admin);
        return result;
    }
}
